package euler.p001_050;

import euler.MainEuler;

public class Euler041 extends MainEuler {

    /*
        We shall say that an n-digit number is pandigital
        if it makes use of all the digits 1 to n exactly once.
        For example, 2143 is a 4-digit pandigital and is also prime.

        What is the largest n-digit pandigital prime that exists?
     */
    public String resolve() {
        // Nine numbers cannot be done (1+2+3+4+5+6+7+8+9=45 => always dividable by 9)
        // Eight numbers cannot be done (1+2+3+4+5+6+7+8=36 => always dividable by 9)

        String digitos = "1234567";

        byte[][] permutaciones = naturalHelper.permutaciones(digitos);
        for (int i = permutaciones.length - 1; i >= 0; i--) {
            int n = toInt(permutaciones[i]);
            if (primeHelper.isPrime(n)) {
                return String.valueOf(n);
            }
        }

        return null;
    }

    private int toInt(byte[] ba) {
        int n = 0;
        for (int i = 0; i < ba.length; i++) {
            n = (10*n+ba[i]);
        }
        return n;
    }

}
